// 复制svg指令 v-copy
import { ElMessage } from 'element-plus'
import { DeElement } from '@/plugins/directives/index'

const copy = {
  beforeMount(el: DeElement) {
    let timer: NodeJS.Timeout
    el._clicks = () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        const text = el.innerText
        if (text) {
          const htmlIcon = `<SvgIcon icon-class="${text}" />`
          navigator.clipboard
            .writeText(htmlIcon)
            .then(() => {
              ElMessage({
                showClose: true,
                message: '复制成功!',
                type: 'success'
              })
            })
            .catch(() => {
              ElMessage({
                showClose: true,
                message: '复制失败,Dom可能为null!',
                type: 'error'
              })
            })
        } else {
          ElMessage({
            showClose: true,
            message: '复制失败,Dom可能为null!',
            type: 'error'
          })
        }
      }, 200)
    }
    el.addEventListener('click', el._clicks)
  },
  unmounted(el: DeElement) {
    el.removeEventListener('click', el._clicks)
  }
}
export default copy
